package com.runen.infinitemovement.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.AMapPara;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.CheckRoadActivity;
import com.runen.infinitemovement.activity.ColumnDetailsActivity;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.activity.LongCollegeActivity;
import com.runen.infinitemovement.activity.MainActivity;
import com.runen.infinitemovement.activity.MyAchievementsActivity;
import com.runen.infinitemovement.activity.RoadLineDetailsActivity;
import com.runen.infinitemovement.activity.SecondReplyCommentActivity;
import com.runen.infinitemovement.activity.SetTargetActivity;
import com.runen.infinitemovement.activity.StepsForActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.adapter.ColumnActivityNameAdapter;
import com.runen.infinitemovement.adapter.ContentsAdapter;
import com.runen.infinitemovement.adapter.MyLongRoadCollegeAdapter;
import com.runen.infinitemovement.adapter.StarRatingAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.AllPathSectionEntity;
import com.runen.infinitemovement.model.entity.AnswerEntity;
import com.runen.infinitemovement.model.entity.AnswerProgressEntity;
import com.runen.infinitemovement.model.entity.CalculateSportgoalEntity;
import com.runen.infinitemovement.model.entity.CollageInfoEntity;
import com.runen.infinitemovement.model.entity.CommentDetailListBean;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MyLongMarchCommentEntity;
import com.runen.infinitemovement.model.entity.MyLongRoadEntity;
import com.runen.infinitemovement.model.entity.PathFixedPointListEntity;
import com.runen.infinitemovement.model.entity.PathPathSectionListEntity;
import com.runen.infinitemovement.model.entity.PathSectionCompleteEntity;
import com.runen.infinitemovement.model.entity.PathSectionListEntity;
import com.runen.infinitemovement.model.entity.PolyLineEntity;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.model.entity.RideRoteJsonEntity;
import com.runen.infinitemovement.model.entity.SaveLongDataEntity;
import com.runen.infinitemovement.model.entity.StepForEntity;
import com.runen.infinitemovement.model.entity.TodayStepForValueEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.AnimationUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.MapUtils;
import com.runen.infinitemovement.tool.map.MapDrawUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.CustomLoadMoreView;
import com.runen.infinitemovement.widget.MapContainer;
import com.runen.infinitemovement.widget.SlidingDrawer;
import com.runen.infinitemovement.widget.goodview.GoodView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.AnswerPopupWindow;
import com.runen.infinitemovement.widget.popupwind.PathSectionCompletePopupWindow;
import com.runen.infinitemovement.widget.popupwind.PersonLongLoadPopupWindow;
import com.runen.infinitemovement.widget.popupwind.ReceiveAwardPopupWindow;
import com.runen.infinitemovement.widget.popupwind.RoadDescPopupWindow;
import com.runen.infinitemovement.widget.popupwind.RoadIntroductionPoppupWindow2;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.infinitemovement.widget.popupwind.SportsPoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import aiven.guide.view.SmartGuide;
import aiven.guide.view.clip.CustomClip;
import aiven.guide.view.face.IntroPanel;
import aiven.guide.view.layer.GuidView;
import aiven.guide.view.util.SmartUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on 2021/01/11 9:44
 */
public class LongRoadFragment extends Fragment {
    @BindView(R.id.mapView)
    TextureMapView mapView;
    @BindView(R.id.tv_no_check)
    TextView tvNoCheck;
    @BindView(R.id.tv_immediately_movement)
    TextView tvImmediatelyMovement;
    @BindView(R.id.tv_step_num)
    TextView tvStepNum;
    @BindView(R.id.ll_steps_for)
    LinearLayout llStepsFor;
    @BindView(R.id.tv_heart_num)
    TextView tvHeartNum;
    @BindView(R.id.iv_heart_img)
    ImageView ivHeartImg;
    @BindView(R.id.ll_heart)
    RelativeLayout llHeart;
    @BindView(R.id.rl_map_top_info)
    RelativeLayout rlMapTopInfo;
    @BindView(R.id.iv_check_road)
    ImageView ivCheckRoad;
    @BindView(R.id.iv_rule_introduce)
    ImageView ivRuleIntroduce;
    @BindView(R.id.tv_road_name)
    TextView tvRoadName;
    @BindView(R.id.tv_road_name_end)
    TextView tvRoadNameEnd;
    @BindView(R.id.tv_challenged_num)
    TextView tvChallengedNum;
    @BindView(R.id.indicator_seek_bar)
    ProgressBar indicatorSeekBar;
    //    @BindView(R.id.tv_road_ranking)
//    TextView tvRoadRanking;
    @BindView(R.id.rv_star)
    RecyclerView rvStar;
    @BindView(R.id.rl_top_info)
    RelativeLayout rlTopInfo;
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.ll_title_info)
    LinearLayout llTitleInfo;
    //    @BindView(R.id.rl_top)
//    RelativeLayout rlTop;
    @BindView(R.id.rv_title)
    RecyclerView rvTitle;
    @BindView(R.id.iv_up_or_down)
    ImageView ivUpOrDown;
    @BindView(R.id.ll_up_or_down)
    LinearLayout llUpOrDown;
    @BindView(R.id.sliding_drawer_content)
    ViewPager slidingDrawerContent;
    @BindView(R.id.slidingDrawer)
    SlidingDrawer slidingDrawer;
    @BindView(R.id.tv_hozom_sum)
    TextView tvHozomSum;
    @BindView(R.id.ll_hozom_finish)
    LinearLayout llHozomFinish;
    @BindView(R.id.rv_content)
    RecyclerView rvContent;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.edt_input_message)
    EditText edtInputMessage;
    @BindView(R.id.rl_bottom)
    LinearLayout rlBottom;
    @BindView(R.id.rl_long_college)
    RelativeLayout rlLongCollege;
    @BindView(R.id.tv_residue_progress)
    TextView tvResidueProgress;
    @BindView(R.id.iv_my_achievements)
    ImageView ivMyAchievements;
    @BindView(R.id.map_container)
    MapContainer mapContainer;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_progress_step)
    TextView tvProgressStep;
    @BindView(R.id.tv_set_target)
    TextView tv_set_target;
    @BindView(R.id.tv_target)
    TextView tv_target;
    @BindView(R.id.tv_target_days)
    TextView tv_target_days;
    @BindView(R.id.tv_start_end_name_1)
    TextView tv_start_end_name_1;
    @BindView(R.id.tv_desc)
    TextView tv_desc;
    @BindView(R.id.iv_answer_gif)
    ImageView iv_answer_gif;
    @BindView(R.id.tv_answer_tips)
    TextView tv_answer_tips;
    @BindView(R.id.iv_answer_close)
    ImageView iv_answer_close;
    //    @BindView(R.id.iv_progressbar)
//    ImageView ivProgressbar;
//    @BindView(R.id.iv_progressbar_2)
//    ImageView ivProgressbar2;
//    @BindView(R.id.iv_progressbar_3)
//    ImageView ivProgressbar3;
    private View view;
    private String[] typeNames = new String[]{"评论留言", "我的成就", "长征故事"};
    private ColumnActivityNameAdapter sportsTypeNameAdapter;
    private List<String> typeList = new ArrayList<>();
    private boolean isOpen;
    private StarRatingAdapter starRatingAdapter;
    private AMap aMap;
    private Polyline polyline;
    private MyLongRoadEntity.DataBean data;
    //    private NoRoadScetionPoppupWindow scetionPoppupWindow;
    private List<PolyLineEntity> polyLineEntityList = new ArrayList<>();
    private PolyLineEntity polyLineEntity;
    private List<PathSectionListEntity> pathSectionListEntityList;
    private double completionRate;
    private String userId;
    private String headImgUrl;
    private ReceiveAwardPopupWindow popupWindow;//路段完成奖励

    private String activity_sectionId;
    private double activity_progress;
    private int activity_type;
    private String startEndName;
    private String activity_count;
    private String activity_day;

    private String roadDesc;//下一段路的介绍
    private boolean isShowRoadDescPopupWindow = false;//是否弹出新路段的介绍

    public AnswerPopupWindow answerPopupWindow;
    public PathSectionCompletePopupWindow pathSectionCompletePopupWindow;

    /**
     * 抽屉滑动随变化监听接口
     */
    private SlidingDrawer.OnDrawerScrollChangedListener onDrawerScrollChangedListener;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.activity_my_the_long_march_road, container, false);
            ButterKnife.bind(this, view);
            EventBus.getDefault().register(this);
            initView(savedInstanceState);
        }
        return view;
    }

    private void initSmartGuide() {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        ivRuleIntroduce.measure(w, h);
        llTitleInfo.measure(w, h);
        int width = ivRuleIntroduce.getMeasuredWidth() + CommonUtil.dp2px(getActivity(), 24);

        float y = llTitleInfo.getMeasuredHeight();
        SmartGuide.newGuide(getActivity())
                .newLayer("rule")
                .buildCustomClip(new SmartGuide.ClipPositionBuilder<CustomClip>() {
                    @Override
                    public CustomClip buildTarget() {//返回一个被挖空的镂空区域实例
                        //构建镂空区域图形，支持CustomClip 和 ViewRectClip，ViewRectClip 后面第二个实例紫色音乐图标实例说明
                        return CustomClip.newClipPos()
                                //设置异形图片(实现见第三个按钮)
                                //.asIrregularShape(getApplicationContext(),R.mipmap.test_img)   这里屏蔽了是因为在实例3中是实现，标识一个要挖空一个异形区域，由不规则图片区域决定
                                .setAlignX(SmartGuide.AlignX.ALIGN_RIGHT)//设置定位水平定位偏向（这里的偏向是屏幕根而言，类似于RelativeLayout的align,局屏幕顶部，左边、右边、下边 自己定义）
                                .setAlignY(SmartGuide.AlignY.ALIGN_TOP)//设置定位垂直定位偏向 （这里的偏向是屏幕根而言，类似于RelativeLayout的align）
                                .setEventPassThrough(false)//镂空区域是否事件穿透，上面说的需要个人中心图标自己响应事件，设置后后面的点击事件 clipClicked 将不再响应改Tag的事件
                                .setOffsetX(SmartUtils.dip2px(getActivity(), 8))//根据水平定位偏向设置偏移，类似于margin，如果未ALIGN_LEFT,则是距离屏幕左侧偏移量，如果是ALIGN_RIGHT 则是距离屏幕右侧偏移量
                                .setOffsetY(y) //同offsetX基本相同的意思，只不过这个是垂直方向的
                                .setClipSize(width, width) //设置镂空裁剪区域尺寸,这里一定要指定，否则没有
                                .clipRadius(width / 2);//设置镂空区域半径，默认是90度直角，也就是方形的，这里显示一个圆圈，所以半径是宽高的一半，也可以自己指定一个圆角值
                    }
                })
                .buildIntroPanel(new SmartGuide.IntroPanelBuilder() {
                    @Override
                    public IntroPanel buildFacePanel() {
                        return IntroPanel.newIntroPanel(getActivity())
                                .setIntroBmp(R.mipmap.ico_my_long_road_guide)//设置一个图片，这里就是刚说那张说明图片
                                //这里的Align 同CustomClip的Align有点点区别，这里的Align不再是界面根布局为标准，这里是clip的镂空区域，也就是局于镂空区域的，左边、上面、下面、右面，自己定义
                                //类似与RelativeLayout的相对布局toLeft、toRight、above、below
                                .setAlign(SmartGuide.AlignX.ALIGN_LEFT, SmartGuide.AlignY.ALIGN_BOTTOM)
                                .setSize(SmartUtils.dip2px(getActivity(), 218), SmartUtils.dip2px(getActivity(), 110)) //设置图片展示的尺寸
                                .setOffset(SmartUtils.dip2px(getActivity(), 10), SmartUtils.dip2px(getActivity(), 10));//设置水平和垂直方向的偏移值，这里要注意根据Align来计算，也相当于margin，不过是相对于clip镂空区域
                    }
                })
                //添加点击事件
                .setOnGuidClickListener(new SmartGuide.OnGuidClickListener() {
                    @Override
                    public boolean emptyErrorClicked(SmartGuide smartGuide) {//点击蒙层中无裁剪和无镂空区域部分，部分需求是点击旁边无内容区域蒙层直接消失，所以这里增加了
                        return true;//返回true，引导消失，false不消失
                    }

                    @Override
                    public void clipClicked(SmartGuide guide, GuidView view, String tag) {
                        //由于设置了setEventPassThrough 为true，所以tag为TAG_USER_HEADER 的时候这里这个方法不会回调
                        if (tag.equals("rule")) {
                            Intent intent = new Intent(getActivity(), WebActivity.class);
                            intent.putExtra("LINK_URL", Constant.RULE_INTRODUCE);
                            startActivity(intent);
                        }
                        guide.dismiss();
                    }

                    @Override
                    public void introClicked(SmartGuide guide, GuidView view, String tag) {
                        //点击文字区域
                    }
                })
                .show();
        SharePreferenceUtils.putBoolean(getActivity(), SPCompat.FIRST_START_MY_LONG_ROAD_RULE, false);
    }

    private void initView(Bundle savedInstanceState) {
        mHandler.sendEmptyMessage(1);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(getActivity(), new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                llTitleInfo.setPadding(0, CommonUtil.getStatusBarHeight(getActivity()), 0, 0);
            }
        });
        if (SharePreferenceUtils.getBoolean(getActivity(), SPCompat.FIRST_START_MY_LONG_ROAD_RULE, true))
            initSmartGuide();
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        mapContainer.setScrollView(scrollView);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        MapUtils.setCustomMap(getActivity(), aMap);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setLogoBottomMargin(-200);
        aMap.getUiSettings().setRotateGesturesEnabled(false);

        Glide.with(this).asGif().load(R.mipmap.ico_answer_gif).into(iv_answer_gif);

        userId = UserAPI.getUserId();
        topBtnLeft.setVisibility(View.INVISIBLE);
//        indicatorSeekBar.setEnabled(false);
        polyLineEntityList = new ArrayList<>();

        initData(true);
        isFirst = true;

//        initSlidingDrawer();
//        onDrawerScrollChange();
        initRating();
//        scetionPoppupWindow = NoRoadScetionPoppupWindow.getInstance(getActivity());

        aMap.setOnPolylineClickListener(new AMap.OnPolylineClickListener() {
            @Override
            public void onPolylineClick(Polyline polyline) {
                List<LatLng> latLngs = polyline.getPoints();
                if (null != polyLineEntityList && polyLineEntityList.size() > 0) {
                    for (int i = 0; i < polyLineEntityList.size(); i++) {
                        if (polyLineEntityList.get(i).latLngs != null && polyLineEntityList.get(i).latLngs.size() > 0) {
                            if (latLngs != null && latLngs.size() > 0) {
                                if (latLngs.get(0).latitude == polyLineEntityList.get(i).latLngs.get(0).latitude &&
                                        latLngs.get(0).longitude == polyLineEntityList.get(i).latLngs.get(0).longitude
                                        && latLngs.get(latLngs.size() - 1).latitude == polyLineEntityList.get(i).latLngs.get(latLngs.size() - 1).latitude
                                        && latLngs.get(latLngs.size() - 1).longitude == polyLineEntityList.get(i).latLngs.get(latLngs.size() - 1).longitude) {
                                    if (null != pathSectionListEntityList && pathSectionListEntityList.size() > 0) {
                                        for (int j = 0; j < pathSectionListEntityList.size(); j++) {
                                            if (polyLineEntityList.get(i).sectionId.equals(pathSectionListEntityList.get(j).sectionId)) {
                                                showPopup(pathSectionListEntityList.get(j));
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        });

        //地图点击区域
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mapList != null && mapList.size() > 0)
                    for (Map.Entry<String, Polygon> entry : mapList.entrySet()) {
                        if (entry.getValue().contains(latLng)) {
                            Intent intent = new Intent(getActivity(), RoadLineDetailsActivity.class);
                            intent.putExtra("pathId", entry.getKey());
                            intent.putExtra(ActivityCompat.MAP_CLICK_YANAN, true);
                            getActivity().startActivity(intent);
                        }
                    }
            }
        });

        llContent.setVisibility(View.GONE);
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY > oldScrollY) {
                    Log.e("=====", "下滑");
                }
                if (scrollY < oldScrollY) {
                    Log.e("=====", "上滑");
                }

                if (scrollY == 0) {
                    Log.e("=====", "滑倒顶部");
                    llContent.setVisibility(View.GONE);
                    isComment = false;
                    rlBottom.setVisibility(View.GONE);
                }

                if (scrollY > (mapView.getMeasuredHeight())) {
                    Log.e("=====", "滑倒底部");
                    llContent.setVisibility(View.VISIBLE);
                } else {
                    llContent.setVisibility(View.GONE);
                    isComment = false;
                    rlBottom.setVisibility(View.GONE);
                }
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    Log.e("=====", "滑倒底部");
                    llContent.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void showPopup(PathSectionListEntity pathSectionListEntity) {
        RoadIntroductionPoppupWindow2 poppupWindow2 = RoadIntroductionPoppupWindow2.getInstance(getActivity(), pathSectionListEntity);
        poppupWindow2.show();
    }

    private void goFor() {
        value = "今日推进<font color='#E22A29'>%s</font>进度值";
        new UserAPI().stepFor(new BaseResultCallback<StepForEntity>() {
            @Override
            public void onResponse(StepForEntity response) {
                if (response.code == 0) {
//                    ToastUtils.showShort(response.data.totalCompletionRatePlus + "");
                    tvProgressStep.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(response.data.totalCompletionRatePlus * 100) + "%")));
                }
            }
        });
    }

    private boolean isFirst;

    /**
     * 目标
     *
     * @param sectionId
     * @param progress
     */
    private void initTarget(String sectionId, double progress) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("sectionId", sectionId);
            jsonObject.put("sectionProgress", 1 - progress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ChallengeAPI().calculateSportGoal(jsonObject.toString(), new BaseResultCallback<CalculateSportgoalEntity>() {
            @Override
            public void onResponse(CalculateSportgoalEntity response) {
                if (response != null && response.code == 0) {
                    int type = response.data.type;
                    String typeStr = type == 1 ? "步" : type == 2 ? "km" : type == 3 ? "km" : "km";
                    String typeName = type == 1 ? "步数" : type == 2 ? "健走" : type == 3 ? "跑步" : "骑行";
                    String text = "每日目标：" + typeName + "%s" + typeStr;
                    tv_target.setText(String.format(text, response.data.number));
                    String text1 = "完成路段约需<font color='#EE581E'> %s <font/>天";
                    tv_target_days.setText(Html.fromHtml(String.format(text1, response.data.day)));
                    activity_type = response.data.type;
                    activity_count = response.data.number + "";
                    activity_day = response.data.day + "";
                }
            }
        });
    }

    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1000:
                    if (timer == null && timerTask == null) {
                        timer = new Timer();
                        timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                mHander.sendEmptyMessage(1001);
                            }
                        };
                        timer.schedule(timerTask, 0, 2000);
                    }
                    break;
                case 1001:
                    if (polyLineEntityList.size() == 0)
                        initMapData();
                    else {
                        if (timer != null && timerTask != null) {
                            timer.cancel();
                            timer = null;
                            timerTask.cancel();
                            timerTask = null;
                        }
                    }
                    break;
            }
        }
    };
    private TimerTask timerTask;
    private Timer timer;

    /**
     * 获取答题
     */
    private void initAnswerList() {
        ((MainActivity) getActivity()).showDialog();
        new ChallengeAPI().getPathAnswerList(new BaseResultCallback<AnswerEntity>() {
            @Override
            public void onResponse(AnswerEntity response) {
                ((MainActivity) getActivity()).dismissDialog();
                if (response != null && response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        answerPopupWindow = AnswerPopupWindow.getInstance(getActivity(), response.data, new AnswerPopupWindow.Inter() {
                            @Override
                            public void inter(int count) {
                                postAnswerProgress(count);
                            }
                        });
                        answerPopupWindow.show();
                    }
                }
            }
        });
    }

    /**
     * 答题更新进度
     *
     * @param rightCount
     */
    private void postAnswerProgress(int rightCount) {
        ((MainActivity) getActivity()).showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("correctNumber", rightCount);
            object.put("sectionId", data.nowSectionInfoDTO.sectionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ChallengeAPI().postPathPathSectionAnswerProgress(object.toString(), new BaseResultCallback<AnswerProgressEntity>() {
            @Override
            public void onResponse(AnswerProgressEntity response) {
                ((MainActivity) getActivity()).dismissDialog();
                if (response != null && response.code == 0) {
                    if (response.data != null) {
                        tv_answer_tips.setText("今日答题已完成，请明日再来～");
                        data.answerStatus = true;
                        if (response.data.correctNumber != 0) {
                            PersonLongLoadPopupWindow window = PersonLongLoadPopupWindow.getInstance(getActivity(), response.data);
                            window.show();
                        }
                    }
                }
            }
        });
    }

    /**
     * 路段完成弹框
     *
     * @param sectionId
     */
    private void getPathSectionCompletePopup(String sectionId) {
        if (TextUtils.isEmpty(sectionId)) return;
        Map<String, Object> params = new HashMap<>();
        params.put("sectionId", sectionId);
        new ChallengeAPI().getPathPathSectionCompletePopup(params, new BaseResultCallback<PathSectionCompleteEntity>() {
            @Override
            public void onResponse(PathSectionCompleteEntity response) {
                if (response != null && response.code == 0) {
                    response.data.pathId = data.nowSectionInfoDTO.pathId;
                    response.data.sectionId = data.nowSectionInfoDTO.sectionId;
                    pathSectionCompletePopupWindow = PathSectionCompletePopupWindow.getInstance(getActivity(),
                            response.data, new PathSectionCompletePopupWindow.DismissClick() {
                                @Override
                                public void click() {
                                    onAutoSiwtchRoad();
                                }
                            });
                    pathSectionCompletePopupWindow.show();
                }
            }
        });
    }

    private void initData(boolean refreshMap) {
//        showDialog("加载地图中...", false);
        String string = "?targetId=%s";
        new ChallengeAPI().myLongRoad(String.format(string, userId), new BaseResultCallback<MyLongRoadEntity>() {
            @Override
            public void onResponse(MyLongRoadEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        data = response.data;
//                        if (refreshMap) {
//                            aMap.clear();
//                        }
                        initContent();
                        setView(data, refreshMap);
//                        initMapData();
                        mHander.sendEmptyMessage(1000);
                        if (!TextUtils.isEmpty(roadDesc) && isShowRoadDescPopupWindow && response.data.nowSectionInfoDTO != null) {
                            isShowRoadDescPopupWindow = false;
                            //切换路线成功，显示下一个路段的故事
                            String startAndEndName = response.data.nowSectionInfoDTO.startPoint + "-" + response.data.nowSectionInfoDTO.endPoint;
                            RoadDescPopupWindow roadDescPopupWindow =
                                    RoadDescPopupWindow.getInstance(getActivity(), startAndEndName,
                                            roadDesc, response.data.nowSectionInfoDTO.sectionId);
                            roadDescPopupWindow.show();
                        }

                        //绘制延安以及小金县范围
                        if (response.data.pathFixedPointList != null) {
                            for (PathFixedPointListEntity pathFixedPointListEntity : response.data.pathFixedPointList) {
                                if (mapList.get(pathFixedPointListEntity.pointId) != null) {
                                    mapList.get(pathFixedPointListEntity.pointId).remove();
                                }
                                if (markerList.get(pathFixedPointListEntity.pointId) != null) {
                                    markerList.get(pathFixedPointListEntity.pointId).remove();
                                }
                                initYanAnPoint(pathFixedPointListEntity.translationFile, pathFixedPointListEntity.pointId);
                                if (!TextUtils.isEmpty(pathFixedPointListEntity.centerPoint))
                                    setMarkerYanAn(pathFixedPointListEntity.pointId,
                                            Double.parseDouble(pathFixedPointListEntity.centerPoint.split(",")[1]),
                                            Double.parseDouble(pathFixedPointListEntity.centerPoint.split(",")[0]),
                                            pathFixedPointListEntity.fixedName);
                            }
                        }
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
            }
        });
    }

    private void initYanAnPoint(String translationFile, String id) {
        new ChallengeAPI().getRideRoteQuery(translationFile, new BaseResultCallback<List<com.runen.infinitemovement.model.entity.RideRoteJsonEntity>>() {
            @Override
            public void onResponse(List<RideRoteJsonEntity> response) {
                if (response != null && response.size() != 0)
                    drawYanAnMap(response, id);
            }
        });
    }

    //根据区块id  存入区块经纬度
    private Map<String, Polygon> mapList = new HashMap<>();
    //根据区块id  存入中心点经纬度
    private Map<String, Marker> markerList = new HashMap<>();

    private void drawYanAnMap(List<RideRoteJsonEntity> rideRoteJsonEntitys, String id) {
        if (aMap == null) return;
        List<LatLng> latLngList = new ArrayList<>();
        for (RideRoteJsonEntity entity : rideRoteJsonEntitys) {
            latLngList.add(new LatLng(entity.latitude, entity.longitude));
        }
        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        // 添加 多边形的每个顶点（顺序添加）
        polygonOptions.addAll(latLngList);
        polygonOptions.strokeWidth(CommonUtil.dp2px(getActivity(), 1)) // 多边形的边框
                .lineJoinType(AMapPara.LineJoinType.LineJoinBevel)
                .strokeColor(getResources().getColor(R.color.color_EA3131)) // 边框颜色
                .fillColor(getResources().getColor(R.color.color_ED2122));   // 多边形的填充色
        Polygon polygon = aMap.addPolygon(polygonOptions);
        mapList.put(id, polygon);
    }

    private String progessId;

    @SuppressLint("NewApi")
    private void setView(MyLongRoadEntity.DataBean data, boolean refreshMap) {
        pathSectionListEntityList = new ArrayList<>();
        if (null != data) {
            String string = "已挑战路段 %s/%s";
            if (data.doneSectionId != null && data.doneSectionId.size() > 0) {
                tvChallengedNum.setText(String.format(string, data.doneSectionId.size(), 29));
            } else {
                tvChallengedNum.setText(String.format(string, 0, 29));
            }
            if (null != data.nowSectionInfoDTO) {
//                llTitleInfo.setBackground(null);
                topBtnRight.setVisibility(View.VISIBLE);
                rlTopInfo.setVisibility(View.VISIBLE);
                rlMapTopInfo.setVisibility(View.VISIBLE);
                tvNoCheck.setVisibility(View.GONE);
//                indicatorSeekBar.setDoubleProgress(data.nowSectionInfoDTO.completionRate * 100);
                indicatorSeekBar.setProgress((int) (data.nowSectionInfoDTO.completionRate * 100));

                //进度为100%，展示领奖弹框
//                data.nowSectionInfoDTO.completionRate = 1;
                if (data.nowSectionInfoDTO.completionRate >= 1) {
//                    showReceiveAward(data.nowSectionInfoDTO.completionRate);
                    getPathSectionCompletePopup(data.nowSectionInfoDTO.sectionId);
                }
                //当前路段概览
                tv_desc.setText(data.nowSectionInfoDTO.introduction);
                tv_start_end_name_1.setText(data.nowSectionInfoDTO.startPoint + " - " + data.nowSectionInfoDTO.endPoint);

                //计算目标
                activity_sectionId = data.nowSectionInfoDTO.sectionId;
                activity_progress = data.nowSectionInfoDTO.completionRate;
                startEndName = data.nowSectionInfoDTO.startPoint + " - " + data.nowSectionInfoDTO.endPoint;
                initTarget(data.nowSectionInfoDTO.sectionId, data.nowSectionInfoDTO.completionRate);
                //今日是否已答题
                if (!data.answerStatus) {
                    tv_answer_tips.setText("快来每日答题领进度，点击答题～");
                } else
                    tv_answer_tips.setText("今日答题已完成，请明日再来～");

//                int width = ivProgressbar.getMeasuredWidth();
//                RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) ivProgressbar2.getLayoutParams();
//                lp1.width = (int) (width * (1 - data.nowSectionInfoDTO.completionRate));
//                ivProgressbar2.setLayoutParams(lp1);
//                RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) ivProgressbar3.getLayoutParams();
//                lp2.width = (int) (width * (1 - data.nowSectionInfoDTO.completionRate)) - CommonUtil.dp2px(getActivity(), 3);
//                ivProgressbar3.setLayoutParams(lp2);

//                if (data.nowSectionInfoDTO.rank == -1) {
//                    tvRoadRanking.setText("--");
//                } else {
//                    tvRoadRanking.setText(String.valueOf(data.nowSectionInfoDTO.rank));
//                }
                String residueProgress = "距目的地剩余：%s";
                tvResidueProgress.setText(String.format(residueProgress, CommonUtil.Double2position(100 - data.nowSectionInfoDTO.completionRate * 100) + "%"));
                tvHeartNum.setText(String.valueOf(data.likeCount));
                completionRate = data.nowSectionInfoDTO.completionRate;
                headImgUrl = data.headImgUrl;
                tvRoadName.setText(data.nowSectionInfoDTO.startPoint);
                tvRoadNameEnd.setText(data.nowSectionInfoDTO.endPoint);
                List<String> difficultys = new ArrayList<>();
                for (int i = 0; i < data.nowSectionInfoDTO.difficulty; i++) {
                    difficultys.add("star");
                }
                starRatingAdapter.setNewData(difficultys);
            } else {
                //自动选择路段
//                llTitleInfo.setBackground(CommonUtil.getDrawable(R.drawable.bg_fffa5438_fff63d5b));
//                topBtnRight.setVisibility(View.INVISIBLE);
//                rlTopInfo.setVisibility(View.GONE);
//                rlMapTopInfo.setVisibility(View.GONE);
//                tvNoCheck.setVisibility(View.VISIBLE);
//                scetionPoppupWindow.show();
//                scetionPoppupWindow.setOnClickListener(new NoRoadScetionPoppupWindow.OnClickListener() {
//                    @Override
//                    public void onClick() {
//                        Intent intent = new Intent(getActivity(), CheckRoadActivity.class);
//                        intent.putExtra("roadData", JsonUtils.toJson(data));
//                        startActivity(intent);
//                        scetionPoppupWindow.dismiss();
//                    }
//                });
            }

            if (refreshMap)
                if (data.pathPathSectionList != null && data.pathPathSectionList.size() > 0) {
                    pathSectionListEntityList.clear();
                    for (int i = 0; i < data.pathPathSectionList.size(); i++) {
                        PathPathSectionListEntity pathPathSectionList = data.pathPathSectionList.get(i);
                        if (pathPathSectionList.pathSectionList != null && pathPathSectionList.pathSectionList.size() > 0) {
                            for (int j = 0; j < pathPathSectionList.pathSectionList.size(); j++) {
                                PathSectionListEntity pathSectionListEntity = pathPathSectionList.pathSectionList.get(j);
                                pathSectionListEntityList.add(pathSectionListEntity);
                            }
                        }
                    }
                }
        }
    }

    private List<SaveLongDataEntity> saveLongDataEntities = new ArrayList<>();
    private SaveLongDataEntity saveLongDataEntity;

    public void setRideRoteQuery(String translationFile, String color, String iconLink, String iconLinkOver,
                                 String icon, String sectionId, double mileage, int difficulty) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new ChallengeAPI().getRideRoteQuery(translationFile, new BaseResultCallback<List<RideRoteJsonEntity>>() {
                    @Override
                    public void onResponse(List<RideRoteJsonEntity> response) {
                        saveLongDataEntity = new SaveLongDataEntity();
                        saveLongDataEntity.color = color;
                        saveLongDataEntity.iconLink = iconLink;
                        saveLongDataEntity.iconLinkOver = iconLinkOver;
                        saveLongDataEntity.roteJsonEntities = response;
                        saveLongDataEntity.sectionId = sectionId;
                        saveLongDataEntity.icon = icon;
                        saveLongDataEntity.mileage = mileage;
                        saveLongDataEntity.difficulty = difficulty;
                        saveLongDataEntities.add(saveLongDataEntity);
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("RideRote", JsonUtils.toJson(saveLongDataEntity));
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                });
            }
        }).start();

    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String str = bundle.getString("RideRote");
                    SaveLongDataEntity saveLongDataEntity = JsonUtils.fromJson(str, SaveLongDataEntity.class);
                    if (saveLongDataEntity != null) {
                        pathPoint(saveLongDataEntity);
                    }
                    break;
                case 2:
                    AnimationUtils.showAndHiddenAnimation(llHozomFinish, AnimationUtils.AnimationState.STATE_HIDDEN, 500);
                    break;
            }

            return false;
        }
    });
    /**
     * 路线展示
     *
     * @param rideRoteJsonEntity
     * @param color
     * @param iconLink
     * @param iconLinkOver
     */
    private List<LatLng> latLngList = new ArrayList<>();
    private LatLngBounds.Builder newBounds = new LatLngBounds.Builder();
    List<RideRoteJsonEntity> rideRoteJsonEntity;

    private void pathPoint(SaveLongDataEntity saveLongDataEntity) {
        polyLineEntity = new PolyLineEntity();
        polyLineEntity.sectionId = saveLongDataEntity.sectionId;
        polyLineEntity.color = saveLongDataEntity.color;
        polyLineEntity.latLngs = new ArrayList<>();
        List<LatLng> latLngs = new ArrayList<>();
        rideRoteJsonEntity = saveLongDataEntity.roteJsonEntities;
        for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
            latLngList.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
            latLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
        }

        polyLineEntity.latLngs.addAll(latLngs);
        polyLineEntityList.add(polyLineEntity);
        setMarker1(latLngs.get(0).latitude, latLngs.get(0).longitude, saveLongDataEntity.iconLink);

        setMarker1(latLngs.get(latLngs.size() - 1).latitude,
                latLngs.get(latLngs.size() - 1).longitude, saveLongDataEntity.iconLink);
        saveLongDataEntity.color = saveLongDataEntity.color.replace("#", "#4d");
        saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                addAll(latLngs)
                .width(10)
                .setDottedLine(true) //打开虚线
                .color(Color.parseColor(saveLongDataEntity.color)));

        List<LatLng> fullLatLngs = new ArrayList<>();
        List<LatLng> xuLatLngs = new ArrayList<>();
        if (data.nowSectionInfoDTO != null) {
            if (data.nowSectionInfoDTO.sectionId.equals(saveLongDataEntity.sectionId)) {
                double lastDistance = saveLongDataEntity.mileage * completionRate;

                for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
                    if (lastDistance < rideRoteJsonEntity.get(i).mileage) {
                        xuLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                    } else {
                        fullLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                    }
                }
                if (xuLatLngs != null && xuLatLngs.size() > 0) {
                    setMarker(xuLatLngs.get(0).latitude, xuLatLngs.get(0).longitude, saveLongDataEntity.iconLink);
                }
                if (fullLatLngs != null && fullLatLngs.size() > 0) {
                    setMarker(fullLatLngs.get(0).latitude, fullLatLngs.get(0).longitude, saveLongDataEntity.iconLinkOver);

                    setMarker2(fullLatLngs.get(fullLatLngs.size() - 1).latitude, fullLatLngs.get(fullLatLngs.size() - 1).longitude);
                }
                saveLongDataEntity.color = saveLongDataEntity.color.replace("#4d", "#");
                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(fullLatLngs)
                        .width(10)
                        .setDottedLine(false) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
//                saveLongDataEntity.color = saveLongDataEntity.color.replace("#4d", "#");
                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(xuLatLngs)
                        .width(10)
                        .setDottedLine(true) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
            }
        }

        List<LatLng> doneLatLngs = new ArrayList<>();
        if (data.doneSectionId != null && data.doneSectionId.size() > 0) {
            for (int i = 0; i < data.doneSectionId.size(); i++) {
                if (data.doneSectionId.get(i).equals(saveLongDataEntity.sectionId)) {
                    for (int j = 0; j < rideRoteJsonEntity.size(); j++) {
                        doneLatLngs.add(new LatLng(rideRoteJsonEntity.get(j).latitude, rideRoteJsonEntity.get(j).longitude));
                    }
                }
            }
            if (doneLatLngs != null && doneLatLngs.size() > 0) {
                setMarker1(doneLatLngs.get(0).latitude, doneLatLngs.get(0).longitude, saveLongDataEntity.iconLinkOver);
                setMarker1(doneLatLngs.get(doneLatLngs.size() - 1).latitude, doneLatLngs.get(doneLatLngs.size() - 1).longitude, saveLongDataEntity.iconLinkOver);
                saveLongDataEntity.polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(doneLatLngs)
                        .width(10)
                        .setDottedLine(false) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
            }
        }


        for (int j = 0; j < latLngList.size(); j++) {
            newBounds.include(new LatLng(latLngList.get(j).latitude, latLngList.get(j).longitude));
        }
        if (aMap != null) {
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(newBounds.build(), 100), null);
        }
    }

    private void setMarkerYanAn(String id, double lat, double lon, String name) {
        View view = View.inflate(App.getInstance().getApplicationContext(), R.layout.view_custom_mark_yanan_text, null);
        TextView tv_yanan = view.findViewById(R.id.tv_yanan);
        tv_yanan.setText(name);
        Marker marker = aMap.addMarker(
                new MarkerOptions()
                        .position(new LatLng(lat, lon))
                        .anchor(name.equals("小金县") ? 1.3f : 0.5f, 0.5f)
                        //添加markerID
                        .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
        markerList.put(id, marker);
    }


    private void setMarker1(double lat, double lon, String img) {
        View view = View.inflate(App.getInstance().getApplicationContext(), R.layout.view_custom_mark_small, null);
        ImageView iv_small = view.findViewById(R.id.iv_small);
        Glide.with(App.getInstance().getApplicationContext()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_small.setImageDrawable(resource);
                Marker markerFlag = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }


    private void setMarker(double lat, double lon, String img) {
        View view = View.inflate(App.getInstance().getApplicationContext(), R.layout.view_custom_mark_flag, null);
        ImageView iv_flag = view.findViewById(R.id.iv_flag);
        Glide.with(App.getInstance().getApplicationContext()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_flag.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.55f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 头像
     *
     * @param lat
     * @param lon
     * @param
     */
    private Marker markerHeader;

    private void setMarker2(double lat, double lon) {
        if (markerHeader != null) {
            markerHeader.remove();
        }
        View view = View.inflate(App.getInstance().getApplicationContext(), R.layout.view_custom_mark, null);
        RoundedCornersImage rc_userHeader = view.findViewById(R.id.rc_userHeader);
        TextView tv_company_name = view.findViewById(R.id.tv_company_name);
        Glide.with(App.getInstance().getApplicationContext()).load(headImgUrl).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                rc_userHeader.setImageDrawable(resource);
                markerHeader = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.55f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 初始化难度View
     */
    private void initRating() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvStar.setLayoutManager(layoutManager);
        starRatingAdapter = new StarRatingAdapter(getActivity());
        rvStar.setAdapter(starRatingAdapter);

    }

    private void onDrawerScrollChange() {
        onDrawerScrollChangedListener = new SlidingDrawer.OnDrawerScrollChangedListener() {
            @Override
            public void onScrollStarted() {
                ivUpOrDown.setImageAlpha(168);
            }

            @Override
            public void onScrollEnded() {
                ivUpOrDown.setImageAlpha(255);
            }

            @Override
            public void onDrawerOpened() {
                AnimationUtils.setRotateAnimation(ivUpOrDown, 0, 180);
                slidingDrawer.lock();
                isOpen = true;
            }

            @Override
            public void onDrawerClosed() {
                AnimationUtils.setRotateAnimation(ivUpOrDown, 180, 0);
                slidingDrawer.unlock();
                isOpen = false;
            }
        };
        slidingDrawer.setOnDrawerScrollChangedListener(onDrawerScrollChangedListener);
    }

    private void initSlidingDrawer() {
        LinearLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        rvTitle.setLayoutManager(layoutManager);
        sportsTypeNameAdapter = new ColumnActivityNameAdapter(getActivity());
        rvTitle.setAdapter(sportsTypeNameAdapter);
        typeList.clear();
        for (int i = 0; i < typeNames.length; i++) {
            typeList.add(typeNames[i]);
        }
        sportsTypeNameAdapter.setNewData(typeList);
        initSportsTypeName();
        sportsTypeNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                sportsTypeNameAdapter.setCheckPosition(position);
                sportsTypeNameAdapter.notifyDataSetChanged();
                slidingDrawerContent.setCurrentItem(position);
            }
        });
    }

    private void initSportsTypeName() {
        slidingDrawerContent.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        ContentsFragment contentsFragment = (ContentsFragment) ContentsFragment.newInstance(userId);
                        return contentsFragment;
                    case 1:
                        MyReflectionFragment myReflectionFragment = (MyReflectionFragment) MyReflectionFragment.newInstance(userId);
                        return myReflectionFragment;
                    case 2:
                        LongMarchStoryFragment longMarchStoryFragment = new LongMarchStoryFragment();
                        return longMarchStoryFragment;
                }
                return null;
            }

            @Override
            public int getCount() {
                return typeList.size();
            }
        });
        slidingDrawerContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                sportsTypeNameAdapter.setCheckPosition(position);
                sportsTypeNameAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @OnClick({R.id.tv_immediately_movement, R.id.ll_heart, R.id.iv_check_road, R.id.iv_rule_introduce, R.id.top_btn_right,
            R.id.ll_up_or_down, R.id.ll_steps_for, R.id.ll_content, R.id.rl_long_college, R.id.iv_my_achievements, R.id.tv_set_target,
            R.id.tv_road_more, R.id.tv_answer_tips, R.id.iv_answer_close, R.id.iv_answer_gif})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_immediately_movement:
                SportsPoppupWindow.getInstance(getActivity()).show();
                break;
            case R.id.ll_heart:
                if (null != data && null != data.nowSectionInfoDTO) {
                    if (data.isLike) {
                        data.isLike = false;
                        data.likeCount--;
                    } else {
                        data.isLike = true;
                        data.likeCount++;
                        GoodView goodView = new GoodView(getActivity());
                        goodView.setImage(R.mipmap.ico_heart);
                        goodView.show(ivHeartImg);
                    }
                    tvHeartNum.setText(String.valueOf(data.likeCount));
                    likeAndCancelLike(data.isLike);
                }
                break;
            case R.id.iv_check_road:
                Intent intent = new Intent(getActivity(), CheckRoadActivity.class);
                intent.putExtra("roadData", JsonUtils.toJson(data));
                startActivity(intent);
                break;
            case R.id.iv_rule_introduce:
                Intent intent1 = new Intent(getActivity(), WebActivity.class);
                intent1.putExtra("LINK_URL", Constant.RULE_INTRODUCE);
                startActivity(intent1);
                break;
            case R.id.top_btn_right:
                showShear();
                break;
            case R.id.ll_up_or_down:
                if (isOpen) {
                    slidingDrawer.unlock();
                    slidingDrawer.animateClose();
                } else {
                    slidingDrawer.animateOpen();
                }
                break;
            case R.id.ll_steps_for:
                Intent intent2 = new Intent(getActivity(), StepsForActivity.class);
                intent2.putExtra("intentFlag", 1);
                startActivityForResult(intent2, 20);
                break;
            case R.id.ll_content:
                isComment = !isComment;
                if (isComment) {
                    rlBottom.setVisibility(View.VISIBLE);
                } else {
                    rlBottom.setVisibility(View.GONE);
                }
                break;
            case R.id.rl_long_college:
                Intent longCollege = new Intent(getActivity(), LongCollegeActivity.class);
                startActivity(longCollege);
                break;
            case R.id.iv_my_achievements:
                Intent intent3 = new Intent(getActivity(), MyAchievementsActivity.class);
                intent3.putExtra("targetId", userId);
                startActivity(intent3);
                break;
            case R.id.tv_set_target:
                if (TextUtils.isEmpty(activity_sectionId)) return;
                Intent intent4 = new Intent(getActivity(), SetTargetActivity.class);
                intent4.putExtra(ActivityCompat.SECTION_ID, activity_sectionId);
                intent4.putExtra(ActivityCompat.PROGRESS, activity_progress);
                intent4.putExtra(ActivityCompat.TYPE, activity_type);
                intent4.putExtra(ActivityCompat.START_END_NAME, startEndName);
                intent4.putExtra(ActivityCompat.COUNT, activity_count);
                intent4.putExtra(ActivityCompat.DAYS, activity_day);
                startActivity(intent4);
                break;
            case R.id.tv_road_more:
                if (data == null) return;
                Intent intent5 = new Intent(getActivity(), RoadLineDetailsActivity.class);
                intent5.putExtra("pathId", data.nowSectionInfoDTO.sectionId);
                getActivity().startActivity(intent5);
                break;
            case R.id.iv_answer_close:
                iv_answer_close.setVisibility(View.GONE);
                tv_answer_tips.setVisibility(View.GONE);
                break;
            case R.id.tv_answer_tips:
                if (data != null && !data.answerStatus)
                    initAnswerList();
                break;
            case R.id.iv_answer_gif:
                if (data != null && !data.answerStatus) {
                    initAnswerList();
                } else {
                    iv_answer_close.setVisibility(View.VISIBLE);
                    tv_answer_tips.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    /**
     * 分享
     */
    private void showShear() {
        SharePoppupWindow.getInstance(getActivity(),
                "我正在挑战「重走长征路」来看看我的进度。",
                "体验不一样的长征路，与我一起挑战吧！",
                String.format(Constant.SHARE_MY_LONG, userId)).show();
    }

    /**
     * 点赞和取消点赞
     *
     * @param isLike
     */
    private void likeAndCancelLike(boolean isLike) {
        JSONObject object = new JSONObject();
        try {
            object.put("beLikeType", 7);
            object.put("likeDataId", UserAPI.getUserId());
            object.put("toLikeUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().myLongMarchLike(object.toString(), isLike, new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    if (isLike) {
                        AnimationUtils.showAndHiddenAnimation(llHozomFinish, AnimationUtils.AnimationState.STATE_SHOW, 3000);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(5000);
                                    handler.sendEmptyMessage(2);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initData(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirst) {
            initData(true);

//            initLongStory();
            isFirst = true;
        }
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mHandler.removeMessages(1);
        EventBus.getDefault().unregister(this);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 100:
                initData(true);
                break;
            case 103://领取奖励成功，关闭弹框，自动切换下一条路
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                onAutoSiwtchRoad();
                break;
            case EventBusEntity.CODE_108:
                initTarget(activity_sectionId, activity_progress);
                break;
            case EventBusEntity.CODE_110:
                value = "今日推进<font color='#E22A29'>%s</font>进度值";
                double totalCompletionRatePlus = event.getData();
                tvProgressStep.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(totalCompletionRatePlus * 100) + "%")));
                break;
            default:
                break;
        }
    }

    /**
     * 自动切换下一条路段
     */
    private void onAutoSiwtchRoad() {
        List<PathPathSectionListEntity> pathPathSectionList = this.data.pathPathSectionList;
        String selectSectionId = null;
        String selectPathId = null;
        if (pathPathSectionList != null && pathPathSectionList.size() > 0) {
            outer:
            for (PathPathSectionListEntity pathEntity : pathPathSectionList) {
                for (PathSectionListEntity entity : pathEntity.pathSectionList) {
                    if (!this.data.doneSectionId.contains(entity.sectionId)
                            && !entity.sectionId.equals(this.data.nowSectionInfoDTO.sectionId)) {
                        selectSectionId = entity.sectionId;
                        selectPathId = pathEntity.pathId;
                        break outer;
                    }
                }
            }
        }
        if (!TextUtils.isEmpty(selectPathId) && !TextUtils.isEmpty(selectSectionId)) {
            onCheck(selectPathId, selectSectionId);
        }
    }

    /**
     * 切换路线
     *
     * @param pathId
     * @param sectionId
     */
    private void onCheck(String pathId, String sectionId) {
        JSONObject object = new JSONObject();
        try {
            object.put("delOldSection", true);
            object.put("sectionId", sectionId);
            object.put("pathId", pathId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ((MainActivity) getActivity()).showDialog();
        new ChallengeAPI().onCheckRoadSection(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                ((MainActivity) getActivity()).dismissDialog();
                roadDesc = response.getData().toString();
                isShowRoadDescPopupWindow = true;
                initData(true);

            }
        });
    }

    private int steps;
    private boolean isUpStep = true;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                steps = StepUtil.getTodayStep(getActivity());
                tvStepNum.setText(String.valueOf(steps));
                if (isUpStep) {
                    if (0 != steps) {
                        onUpDataStep();
                        isUpStep = false;
                    }
                }
                mHandler.sendEmptyMessageDelayed(1, 3000);
            }
            return false;
        }
    });

    private void onUpDataStep() {
        JSONObject object = new JSONObject();
        try {
            object.put("step", steps);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().upDataStep(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                } else {
//                    initDataProgress();
                }
                goFor();
            }
        });
    }

    private String value;

    private void initDataProgress() {
        value = "今日推进<font color='#E22A29'>%s</font>进度值";
        new UserAPI().getStep(new BaseResultCallback<TodayStepForValueEntity>() {
            @Override
            public void onResponse(TodayStepForValueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        tvProgressStep.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(response.data.completionRatePlus * 100) + "%")));
                    }
                } else {
                    tvProgressStep.setText(Html.fromHtml(String.format(value, 0)));
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intentData) {
        super.onActivityResult(requestCode, resultCode, intentData);
        if (resultCode == 20) {
            if (intentData != null) {
                value = "今日推进<font color='#E22A29'>%s</font>进度值";
//                Log.e("11111111111", "onActivityResult: 111111111111" );
                double completionRatePlus = intentData.getDoubleExtra("completionRatePlus", 0);
                double totalCompletionRatePlus = intentData.getDoubleExtra("totalCompletionRatePlus", 0);
                completionRate = completionRate + completionRatePlus;
//                indicatorSeekBar.setDoubleProgress(completionRate * 100);
                indicatorSeekBar.setProgress((int) (completionRate * 100));
                tvProgressStep.setText(Html.fromHtml(String.format(value, CommonUtil.Double2position(totalCompletionRatePlus * 100) + "%")));

//                showReceiveAward(completionRate);
                if (completionRate >= 1)
                    getPathSectionCompletePopup(data.nowSectionInfoDTO.sectionId);
            }
        }
    }

    /**
     * 展示领奖弹框
     *
     * @param completionRate 当前路段进度
     */
    public void showReceiveAward(double completionRate) {
        if (completionRate >= 1) {
            //弹出 领奖弹框
            if (!TextUtils.isEmpty(this.data.nowSectionInfoDTO.prizeName) && !this.data.nowSectionInfoDTO.prizeReceiveStatus) {
                popupWindow = ReceiveAwardPopupWindow.getInstance(getActivity(),
                        this.data.nowSectionInfoDTO.prizeName,
                        this.data.nowSectionInfoDTO.prizeUrl,
                        "金沙江-大渡河", this.data.nowSectionInfoDTO.pathId, this.data.nowSectionInfoDTO.sectionId);
                popupWindow.show();
            } else {
                onAutoSiwtchRoad();
            }
        }
    }

    /**
     * 留言信息
     */
    private ContentsAdapter contentsAdapter;
    private CommentDetailListBean commentDetailListBean;
    private ReplyCommentListBean replyCommentListBean;
    private String topItemCommentId;

    private void initContent() {
        initContentData();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvContent.setLayoutManager(layoutManager);
        contentsAdapter = new ContentsAdapter(getActivity());
        contentsAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        rvContent.setAdapter(contentsAdapter);


        contentsAdapter.setOnItemCommentClick(new ContentsAdapter.OnItemCommentClick() {
            @Override
            public void onItemPraise(CommentDetailListBean item) {

            }

            @Override
            public void onItemCommentReply(CommentDetailListBean item, String topCommentId) {
//                //评论回复
//                commentDetailListBean = item;
//                topItemCommentId = topCommentId;
//                edtInputMessage.setHint("回复" + item.nickname + "：");
//                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemSecondReply(ReplyCommentListBean item, String topCommentId) {
//                replyCommentListBean = item;
//                topItemCommentId = topCommentId;
//                edtInputMessage.setHint("回复" + item.reviewerName + "：");
//                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemMore(CommentDetailListBean item, String topCommentId) {
                Intent intent = new Intent(getActivity(), SecondReplyCommentActivity.class);
                intent.putExtra("commentId", item.commentId);
                intent.putExtra("targetId", userId);
                startActivity(intent);
            }
        });

        edtInputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentDetailListBean, replyCommentListBean);
                    }
                }
                return false;
            }
        });
//        iniLoadMore();
    }

//    private void iniLoadMore() {
//        contentsAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                loadMoreRequested();
//            }
//        });
//        contentsAdapter.getLoadMoreModule().setAutoLoadMore(true);
//        contentsAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
//    }


    /**
     * 对文章的评论
     *
     * @param edtString
     */
    private void onComment(String edtString, final CommentDetailListBean commentDetailList, final ReplyCommentListBean replyCommentList) {
        if (data == null || data.nowSectionInfoDTO == null) return;
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "2");
            object.put("content", edtString);
            object.put("targetId", data.nowSectionInfoDTO.sectionId);
            object.put("replyUserId", userId);
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(getActivity());
                edtInputMessage.setText("");
                edtInputMessage.setHint("说点什么...");
                commentDetailListBean = null;
                replyCommentListBean = null;
                initContentData();
            }
        });
    }


    private boolean isComment;

    private void initContentData() {
        if (data == null || data.nowSectionInfoDTO == null) return;
        String string = "?commentType=2&limit=50&page=1&targetId=" + data.nowSectionInfoDTO.sectionId;
//        new ActivityAPI().getMyLongMarchComment(string, new BaseResultCallback<MyLongMarchCommentEntity>() {
//            @Override
//            public void onResponse(MyLongMarchCommentEntity response) {
//                if (response.code == 0) {
//                    if (response.data != null && response.data.size() > 0) {
//                        contentsAdapter.setNewData(response.data);
//                        if (contentsAdapter.getData().size() >= response.count) {
//                            contentsAdapter.getLoadMoreModule().loadMoreEnd(true);
//                            contentsAdapter.getLoadMoreModule().setEnableLoadMore(false);
//                        }
//                    }
//                }
//            }
//        });
        new ActivityAPI().getMyLongMarchCommentV2(string, new BaseResultCallback<MyLongMarchCommentEntity>() {
            @Override
            public void onResponse(MyLongMarchCommentEntity response) {
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        contentsAdapter.setNewData(response.data);
                        if (contentsAdapter.getData().size() >= response.count) {
                            contentsAdapter.getLoadMoreModule().loadMoreEnd(true);
                            contentsAdapter.getLoadMoreModule().setEnableLoadMore(false);
                        }
                    }
                }
            }
        });
    }


    /**
     * 长征故事
     */
    @BindView(R.id.rv_long_march_story)
    RecyclerView rvLongMarchStory;
    private MyLongRoadCollegeAdapter columnAdapter;

    private void initLongStory() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvLongMarchStory.setLayoutManager(layoutManager);
        columnAdapter = new MyLongRoadCollegeAdapter(getActivity());
        rvLongMarchStory.setAdapter(columnAdapter);

        columnAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), ColumnDetailsActivity.class);
                intent.putExtra("informationId", columnAdapter.getData().get(position).informationId);
                startActivity(intent);
            }
        });
        initLongStoryData();
    }

    private void initLongStoryData() {
        String string = "?limit=3&page=1";
        new ActivityAPI().getMyLongCollageInfo(string, new BaseResultCallback<CollageInfoEntity>() {
            @Override
            public void onResponse(CollageInfoEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        columnAdapter.setNewData(response.data.informationList);
                    }
                }

            }
        });
    }

    /**
     * 地图数据
     */
    private void initMapData() {
        if (polyLineEntityList.size() > 0) return;//该list有值则不重新绘制
        ChallengeAPI api = new ChallengeAPI();
        if (api.getMapPathSection() != null)
            polyLineEntityList = MapDrawUtils.setMapData(aMap, data, api.getMapPathSection(), headImgUrl);
        String version = api.getMapPathSectionVersion();
        List<AllPathSectionEntity.DataBean> pathSectionDatas = api.getMapPathSection();
        api.getPathSectionVersion(new BaseResultCallback<BaseResponseEntity>() {
            @Override
            public void onResponse(BaseResponseEntity response) {
                if (!response.getData().equals(version)
                        || pathSectionDatas == null || pathSectionDatas.size() == 0) {
                    api.saveMapPathSectionVersion(response.getData().toString());
                    api.getPathSectionLatAndLon(new BaseResultCallback<AllPathSectionEntity>() {
                        @Override
                        public void onResponse(AllPathSectionEntity response) {
                            if (response.code == 0 && response.data != null) {
                                api.saveMapPathSection(response.data);
                                polyLineEntityList = MapDrawUtils.setMapData(aMap, data, response.data, headImgUrl);
                            }
                        }
                    });
                }
            }
        });
    }


}
